package com.tian.arch.base

import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.Window
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import com.tian.arch.Foundation
import com.tian.arch.util.observe
import kotlinx.coroutines.launch


interface IView {
    /**
     * 提供基本 UI 交互方法，包括进度条和 toast 等。
     */
    val displayDelegate: IDisplay

    /**
     * 提供 Disposable 管理的功能，会自动管理生命周期。
     */
    val disposableManager: IDisposableManager
}


abstract class BaseActivity<VM : BaseViewModel, VB : ViewBinding>(val inflate: (LayoutInflater) -> VB) : AppCompatActivity(), IView {

    override val displayDelegate by lazy { Foundation.globalConfig().displayDelegate.invoke() }
    override val disposableManager by lazy { DisposeManager() }

    protected lateinit var vb: VB
    protected abstract val vm: VM

    private var subscribedLoading = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        beforeSetContent()
        setContent()
        afterSetContent()
        subscribeLoading()
        initPage()
    }

    abstract fun initPage()

    protected open fun beforeSetContent() {
        setStatusBarLightMode(window, true)
        disposableManager.init(this)
    }

    protected open fun afterSetContent() {
        displayDelegate.init(this)
    }

    protected open fun setContent(): View {
        vb = inflate(layoutInflater)
        setContentView(vb.root)
        return vb.root
    }

    open fun subscribeLiveData() {
    }

    private fun subscribeLoading() {
        if (subscribedLoading) return
        observe(vm.loading) {
            when (it) {
                is LoadingState.Loading -> displayDelegate.showLoadingDialog(it.message)
                is LoadingState.Hide -> displayDelegate.dismissLoadingDialog()
            }
        }
        subscribedLoading = true
    }

    private fun setStatusBarLightMode(
        window: Window,
        isLightMode: Boolean
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val decorView = window.decorView
            var vis = decorView.systemUiVisibility
            vis = if (isLightMode) {
                vis or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            } else {
                vis and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
            }
            decorView.systemUiVisibility = vis
        }
    }
}